package cn.sunshuai.xhr;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.util.List;

public class Consumer {
    public static void main(String[] args) throws Exception {
        //创建消费者组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("xhr-consumer-group");
        //设置nameServer地址
        consumer.setNamesrvAddr("127.0.0.1:9876");
        //订阅topic，指定tag标签
        consumer.subscribe("topic","pet");
        //注册消息监听器
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    for (MessageExt messageExt : list) {
                        String body = new String(messageExt.getBody(), RemotingHelper.DEFAULT_CHARSET);
                        System.out.println(body);
                    }

                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                
            }
        });
        //开启消费者
        consumer.start();


    }
}


